import React, { useState, useEffect } from 'react';
import { useTranslation } from 'react-i18next';
import { useNavigate } from 'react-router-dom';
import authService from '../services/authService';
import { validateEmail, validatePassword, validatePhone, validateVerificationCode, generateMockVerificationCode } from '../utils/validators';
import { LOGIN_FORM_FIELDS, ERROR_MESSAGES } from '../constants/formFields';
import CaptchaModal from './CaptchaModal';
import './FormStyles.css';

const LoginForm = ({ switchMode }) => {
  const { t } = useTranslation();
  const navigate = useNavigate();
  const [loginType, setLoginType] = useState('email'); // 'email' or 'phone'
  const [formData, setFormData] = useState({
    [LOGIN_FORM_FIELDS.EMAIL]: '',
    [LOGIN_FORM_FIELDS.PHONE]: '',
    [LOGIN_FORM_FIELDS.PASSWORD]: '',
    [LOGIN_FORM_FIELDS.VERIFICATION_CODE]: '',
    [LOGIN_FORM_FIELDS.REMEMBER_ME]: false,
    [LOGIN_FORM_FIELDS.LOGIN_TYPE]: 'email'
  });
  
  const [errors, setErrors] = useState({});
  const [isLoading, setIsLoading] = useState(false);
  const [countdown, setCountdown] = useState(0);
  const [mockVerificationCode, setMockVerificationCode] = useState('');
  const [isCaptchaValid, setIsCaptchaValid] = useState(false);
  const [showCaptchaModal, setShowCaptchaModal] = useState(false);

  const handleChange = (e) => {
    const { name, value, type, checked } = e.target;
    setFormData(prev => ({
      ...prev,
      [name]: type === 'checkbox' ? checked : value
    }));
    
    // Clear error when user starts typing
    if (errors[name]) {
      setErrors(prev => ({ ...prev, [name]: '' }));
    }
  };

  useEffect(() => {
    let timer;
    if (countdown > 0) {
      timer = setTimeout(() => setCountdown(countdown - 1), 1000);
    }
    return () => clearTimeout(timer);
  }, [countdown]);

  const handleLoginTypeChange = (type) => {
    setLoginType(type);
    setFormData(prev => ({
      ...prev,
      [LOGIN_FORM_FIELDS.LOGIN_TYPE]: type,
      [LOGIN_FORM_FIELDS.EMAIL]: '',
      [LOGIN_FORM_FIELDS.PHONE]: '',
      [LOGIN_FORM_FIELDS.PASSWORD]: '',
      [LOGIN_FORM_FIELDS.VERIFICATION_CODE]: ''
    }));
    setErrors({});
    setIsCaptchaValid(false);
  };

  const sendVerificationCode = () => {
    if (loginType === 'phone') {
      if (!formData[LOGIN_FORM_FIELDS.PHONE]) {
        setErrors({ [LOGIN_FORM_FIELDS.PHONE]: t('loginForm.phoneRequired') });
        return;
      }
      if (!validatePhone(formData[LOGIN_FORM_FIELDS.PHONE])) {
        setErrors({ [LOGIN_FORM_FIELDS.PHONE]: t('loginForm.phoneInvalid') });
        return;
      }
    }
    
    // Generate mock verification code
    const code = generateMockVerificationCode();
    setMockVerificationCode(code);
    
    // In a real app, this would send the code via SMS
    alert(`${t('loginForm.verificationCodeSent')}: ${code}`);
    
    // Start countdown
    setCountdown(60);
  };

  const validateForm = () => {
    const newErrors = {};
    
    if (loginType === 'email') {
      if (!formData[LOGIN_FORM_FIELDS.EMAIL]) {
        newErrors[LOGIN_FORM_FIELDS.EMAIL] = t('loginForm.emailRequired');
      } else if (!validateEmail(formData[LOGIN_FORM_FIELDS.EMAIL])) {
        newErrors[LOGIN_FORM_FIELDS.EMAIL] = t('loginForm.emailInvalid');
      }
      
      if (!formData[LOGIN_FORM_FIELDS.PASSWORD]) {
        newErrors[LOGIN_FORM_FIELDS.PASSWORD] = t('loginForm.passwordRequired');
      } else if (formData[LOGIN_FORM_FIELDS.PASSWORD].length < 1) {
        newErrors[LOGIN_FORM_FIELDS.PASSWORD] = t('loginForm.passwordMinLength');
      }
    } else {
      if (!formData[LOGIN_FORM_FIELDS.PHONE]) {
        newErrors[LOGIN_FORM_FIELDS.PHONE] = t('loginForm.phoneRequired');
      } else if (!validatePhone(formData[LOGIN_FORM_FIELDS.PHONE])) {
        newErrors[LOGIN_FORM_FIELDS.PHONE] = t('loginForm.phoneInvalid');
      }
      
      if (!formData[LOGIN_FORM_FIELDS.VERIFICATION_CODE]) {
        newErrors[LOGIN_FORM_FIELDS.VERIFICATION_CODE] = t('loginForm.verificationCodeRequired');
      } else if (!validateVerificationCode(formData[LOGIN_FORM_FIELDS.VERIFICATION_CODE])) {
        newErrors[LOGIN_FORM_FIELDS.VERIFICATION_CODE] = t('loginForm.verificationCodeInvalid');
      } else if (formData[LOGIN_FORM_FIELDS.VERIFICATION_CODE] !== mockVerificationCode) {
        newErrors[LOGIN_FORM_FIELDS.VERIFICATION_CODE] = t('loginForm.verificationCodeInvalid');
      }
    }
    
    // 验证码验证将在弹出模态框中进行，这里不再检查
    
    return newErrors;
  };

  const handleSubmit = async (e) => {
    e.preventDefault();
    const newErrors = validateForm();
    
    if (Object.keys(newErrors).length > 0) {
      setErrors(newErrors);
      return;
    }
    
    // 显示验证码模态框而不是直接提交
    setShowCaptchaModal(true);
  };

  const handleCaptchaVerified = () => {
    setIsCaptchaValid(true);
    setIsLoading(true);
    
    // Simulate login process without API call
    setTimeout(() => {
      // Store a mock token to simulate authentication
      localStorage.setItem('mockAuthToken', 'demo-token');
      
      let userData;
      if (loginType === 'email') {
        userData = {
          name: formData[LOGIN_FORM_FIELDS.EMAIL].split('@')[0],
          email: formData[LOGIN_FORM_FIELDS.EMAIL]
        };
      } else {
        userData = {
          name: 'User' + formData[LOGIN_FORM_FIELDS.PHONE].slice(-4),
          phone: formData[LOGIN_FORM_FIELDS.PHONE]
        };
      }
      
      localStorage.setItem('mockUser', JSON.stringify(userData));
      
      setIsLoading(false);
      setShowCaptchaModal(false);
      alert(t('loginForm.loginSuccess'));
      
      // Redirect to landing page
      navigate('/');
    }, 1500);
  };

  return (
    <form className="auth-form" onSubmit={handleSubmit}>
      {errors.general && (
        <div className="error-message general-error">
          {errors.general}
        </div>
      )}
      
      {/* Login Type Toggle */}
      <div className={`login-type-toggle ${loginType === 'phone' ? 'phone-active' : ''}`}>
        <button
          type="button"
          className={`toggle-btn ${loginType === 'email' ? 'active' : ''}`}
          onClick={() => handleLoginTypeChange('email')}
        >
          {t('loginForm.loginWithEmail')}
        </button>
        <button
          type="button"
          className={`toggle-btn ${loginType === 'phone' ? 'active' : ''}`}
          onClick={() => handleLoginTypeChange('phone')}
        >
          {t('loginForm.loginWithPhone')}
        </button>
      </div>
      
      {loginType === 'email' ? (
        <>
          <div className="form-group">
            <label htmlFor={LOGIN_FORM_FIELDS.EMAIL} className="form-label">{t('loginForm.emailLabel')}</label>
            <div className="input-wrapper">
              <input
                type="email"
                id={LOGIN_FORM_FIELDS.EMAIL}
                name={LOGIN_FORM_FIELDS.EMAIL}
                className={`form-input ${errors[LOGIN_FORM_FIELDS.EMAIL] ? 'error' : ''}`}
                placeholder={t('loginForm.emailPlaceholder')}
                value={formData[LOGIN_FORM_FIELDS.EMAIL]}
                onChange={handleChange}
                disabled={isLoading}
              />
              {errors[LOGIN_FORM_FIELDS.EMAIL] && (
                <span className="error-icon">⚠️</span>
              )}
            </div>
            {errors[LOGIN_FORM_FIELDS.EMAIL] && (
              <span className="error-message">{errors[LOGIN_FORM_FIELDS.EMAIL]}</span>
            )}
          </div>
          
          <div className="form-group">
            <label htmlFor={LOGIN_FORM_FIELDS.PASSWORD} className="form-label">{t('loginForm.passwordLabel')}</label>
            <div className="input-wrapper">
              <input
                type="password"
                id={LOGIN_FORM_FIELDS.PASSWORD}
                name={LOGIN_FORM_FIELDS.PASSWORD}
                className={`form-input ${errors[LOGIN_FORM_FIELDS.PASSWORD] ? 'error' : ''}`}
                placeholder={t('loginForm.passwordPlaceholder')}
                value={formData[LOGIN_FORM_FIELDS.PASSWORD]}
                onChange={handleChange}
                disabled={isLoading}
              />
              {errors[LOGIN_FORM_FIELDS.PASSWORD] && (
                <span className="error-icon">⚠️</span>
              )}
            </div>
            {errors[LOGIN_FORM_FIELDS.PASSWORD] && (
              <span className="error-message">{errors[LOGIN_FORM_FIELDS.PASSWORD]}</span>
            )}
          </div>
        </>
      ) : (
        <>
          <div className="form-group">
            <label htmlFor={LOGIN_FORM_FIELDS.PHONE} className="form-label">{t('loginForm.phoneLabel')}</label>
            <div className="input-wrapper">
              <input
                type="tel"
                id={LOGIN_FORM_FIELDS.PHONE}
                name={LOGIN_FORM_FIELDS.PHONE}
                className={`form-input ${errors[LOGIN_FORM_FIELDS.PHONE] ? 'error' : ''}`}
                placeholder={t('loginForm.phonePlaceholder')}
                value={formData[LOGIN_FORM_FIELDS.PHONE]}
                onChange={handleChange}
                disabled={isLoading}
              />
              {errors[LOGIN_FORM_FIELDS.PHONE] && (
                <span className="error-icon">⚠️</span>
              )}
            </div>
            {errors[LOGIN_FORM_FIELDS.PHONE] && (
              <span className="error-message">{errors[LOGIN_FORM_FIELDS.PHONE]}</span>
            )}
          </div>
          
          <div className="form-group">
            <label htmlFor={LOGIN_FORM_FIELDS.VERIFICATION_CODE} className="form-label">{t('loginForm.verificationCodeLabel')}</label>
            <div className="input-wrapper with-button">
              <input
                type="text"
                id={LOGIN_FORM_FIELDS.VERIFICATION_CODE}
                name={LOGIN_FORM_FIELDS.VERIFICATION_CODE}
                className={`form-input ${errors[LOGIN_FORM_FIELDS.VERIFICATION_CODE] ? 'error' : ''}`}
                placeholder={t('loginForm.verificationCodePlaceholder')}
                value={formData[LOGIN_FORM_FIELDS.VERIFICATION_CODE]}
                onChange={handleChange}
                disabled={isLoading}
                maxLength={6}
              />
              <button
                type="button"
                className="verification-code-btn"
                onClick={sendVerificationCode}
                disabled={isLoading || countdown > 0}
              >
                {countdown > 0 ? `${countdown} ${t('loginForm.seconds')}` : t('loginForm.sendVerificationCode')}
              </button>
              {errors[LOGIN_FORM_FIELDS.VERIFICATION_CODE] && (
                <span className="error-icon">⚠️</span>
              )}
            </div>
            {errors[LOGIN_FORM_FIELDS.VERIFICATION_CODE] && (
              <span className="error-message">{errors[LOGIN_FORM_FIELDS.VERIFICATION_CODE]}</span>
            )}
          </div>
        </>
      )}
      
      
      <div className="form-options">
        <label className="checkbox-label">
          <input
            type="checkbox"
            name={LOGIN_FORM_FIELDS.REMEMBER_ME}
            checked={formData[LOGIN_FORM_FIELDS.REMEMBER_ME]}
            onChange={handleChange}
            disabled={isLoading}
          />
          <span className="checkmark"></span>
          {t('loginForm.rememberMe')}
        </label>
        
        <a href="#" className="forgot-password">{t('loginForm.forgotPassword')}</a>
      </div>
      
      <button 
        type="submit" 
        className="submit-btn"
        disabled={isLoading}
      >
        {isLoading ? (
          <span className="loading-spinner"></span>
        ) : (
          t('loginForm.loginButton')
        )}
      </button>
      
      <div className="switch-auth">
        {t('loginForm.noAccount')}
        <button
          type="button"
          className="switch-btn"
          onClick={switchMode}
          disabled={isLoading}
        >
          {t('loginForm.registerNow')}
        </button>
      </div>
      
      {/* Captcha Modal */}
      <CaptchaModal
        isOpen={showCaptchaModal}
        onClose={() => setShowCaptchaModal(false)}
        onVerify={handleCaptchaVerified}
        title={t('captcha.verification')}
      />
    </form>
  );
};

export default LoginForm;